package org.example.jsoup;

import com.google.gson.Gson;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo1 {

        public static void main(String[] args) throws IOException {
            String addr = "https://www.jiushujie.com/";
            URL url = new URL(addr);
            Document doc = Jsoup.parse(url,5000);
            Elements elements = doc.select("div.book_list li>a");
            for (Element element : elements) {
                String href = element.attr("href");
                String id = href.replaceAll("\\D","");
                downBookInfo(id);
            }
        }


        public static void downBookInfo(String id) throws IOException {
        String addr = "https://www.jiushujie.com/sell/" + id;
        URL url = new URL(addr);

        Map<String, String> book = new HashMap<>();
        Document doc =  Jsoup.parse(url,5000);
        book.put("image",doc.selectFirst("div.book_item div.book_pic>img").attr("src"));
        book.put("name",doc.selectFirst("div.book_item div.info>h2").text());
        String detail = doc.selectFirst("div.book_item div.detail").text();
        detail = detail.trim();
        String[] details = detail.split("[\\s\\n/]+");
        book.put("press",details[0]);
        book.put("arthor",details[1]);
        book.put("isbn",details[2]);
        book.put("price1",details[3].substring(1));
        book.put("price2",details[4].substring(2));
        book.put("old",details[5]);
        book.put("category",details[6]);
        if (doc.selectFirst("div.book_introduction_container") != null) {
            book.put("intro",doc.selectFirst("div.book_introduction_container").html());

        }
        System.out.println("book = " + book);
    }

    public static void main1(String[] args) throws IOException {

        String url = "https://www.vvic.com/apif/v1/searchPage/rec?city=gz";
        URL u = new URL(url);

        URLConnection urlConnection = u.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader br = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        Gson gson = new Gson();
        HashMap hashMap = gson.fromJson(sb.toString(), HashMap.class);

        List data = (List) hashMap.get("data");
        for (Object d : data) {
            System.out.println(d);
        }
    }
}
